<template>
    <div :class="{ 'dark-mode': isDark }" class="upload-container">
        <el-header class="header">
            <div class="container">
                <h1 class="title">应用上传</h1>
                <el-switch v-model="isDark" active-text="暗黑模式" inactive-text="明亮模式" @change="toggleDarkMode" />
            </div>
        </el-header>

        <el-main class="main">
            <el-card class="upload-card" shadow="always">
                <el-form ref="uploadForm" :model="form" :rules="rules" label-position="top">
                    <!-- 应用名称 -->
                    <el-form-item label="应用名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入应用名称" clearable />
                    </el-form-item>
                    <!--应用链接  -->
                    <el-form-item label="应用链接" prop="name">
                        <el-input v-model="form.link" placeholder="请输入应用链接" clearable />
                    </el-form-item>

                    <!-- 应用分类 -->
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="分类" prop="category">
                                <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                                    <el-option v-for="item in categories" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <!-- 版本号 -->
                        <el-col :span="12">
                            <el-form-item label="版本号" prop="version">
                                <el-input v-model="form.version" placeholder="格式如：1.0.0" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- 更新日期 -->


                    <!-- 应用描述 -->
                    <el-form-item label="应用描述" prop="description">
                        <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入应用描述（最多200字）"
                            maxlength="200" show-word-limit />
                    </el-form-item>

                    <!-- 图标上传 -->
                    <el-form-item label="应用图标" prop="icon">
                        <el-upload class="icon-uploader" action="#" :show-file-list="false"
                            :before-upload="beforeIconUpload" :http-request="handleIconUpload">
                            <!-- 修改这里：始终显示默认图标，上传后覆盖 -->
                            <img v-if="form.icon" :src="form.icon" class="icon-preview">
                            <div v-else class="default-icon">
                                <img :src="defaultIcon" class="icon-preview">
                                <div class="upload-mask">
                                    <el-icon class="upload-icon">
                                        <Plus />
                                    </el-icon>
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <!-- 提交按钮 -->
                    <el-form-item>
                        <el-button type="primary" @click="submitForm" :loading="submitting">
                            提交应用
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </el-main>
    </div>
</template>
  
<script setup>
import { ref, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { $_upload } from "@/api/yh.js";
// 新增默认图标常量
const defaultIcon = 'https://shopimg.cloudvast.com/ico/qtsy.ico'
// 暗黑模式状态（保持与之前页面一致）
const isDark = ref(localStorage.getItem('darkMode') === 'true' || false)

// 表单数据
const form = reactive({
    name: '',
    link: '',
    category: '',
    version: '',
    description: '',
    icon: defaultIcon
})

// 表单验证规则
const rules = reactive({
    name: [
        { required: true, message: '请输入应用名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    link: [
        { required: true, message: '请输入应用链接', trigger: 'blur' },
    ],
    category: [
        { required: true, message: '请选择分类', trigger: 'change' }
    ],
    version: [
        { required: true, message: '请输入版本号', trigger: 'blur' },
        { pattern: /^\d+\.\d+\.\d+$/, message: '版本号格式不正确', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入应用描述', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],

})

// 分类选项
const categories = ref([
    { label: '收银', value: 'cashier' },
])

// 图标上传处理
const beforeIconUpload = (file) => {
    const isImage = ['image/jpeg', 'image/png'].includes(file.type)
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('只能上传 JPG/PNG 格式!')
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
    }
    return isImage && isLt2M
}

const handleIconUpload = async ({ file }) => {
    // 这里实现实际上传逻辑（示例用 base64）
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
        form.icon = reader.result
    }
}

// 表单提交
const submitting = ref(false)
const uploadForm = ref(null)

const submitForm = async () => {
    try {
        await uploadForm.value.validate()
        submitting.value = true
        $_upload(form).then(res => {
            if (res.success) {
                ElMessage.success('应用提交成功！')
            }
        })

        // 重置表单
        uploadForm.value.resetFields()
    } catch (err) {
        ElMessage.error('应用提交失败')
        console.error('验证失败:', err)
    } finally {
        submitting.value = false
    }
}
</script>
  
<style scoped>
.upload-container {
    min-height: 100vh;
    transition: background 0.3s, color 0.3s;
}

/* 暗黑模式适配 */
.upload-container.dark-mode {
    background: #141414;
    color: #e5eaf3;
}

.upload-card {
    max-width: 800px;
    margin: 20px auto;
    padding: 20px;
}

.icon-uploader {
    width: 150px;
    height: 150px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
}

.icon-uploader:hover {
    border-color: var(--el-color-primary);
}

.uploader-icon {
    font-size: 28px;
    color: var(--el-text-color-secondary);
    width: 150px;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.icon-preview {
    width: 100%;
    height: 100%;
    object-fit: contain;
    vertical-align: top;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .upload-card {
        margin: 10px;
        padding: 15px;
    }

    .el-col {
        width: 100%;
        margin-bottom: 10px;
    }
}
.header{
    display:flex;
    justify-content:center;
    align-items:center;
}
</style>